#include "unp.h"
#include <sys/select.h>

void str_cli(FILE *fp, int fd)
{
    char readline[MAXLINE], recvline[MAXLINE];
    fd_set fdset;
    int max_fd;
    int stdioeof = 1;
    ssize_t n;

    for ( ; ; ) {
        FD_ZERO(&fdset);
        FD_SET(fd, &fdset);
        FD_SET(fileno(fp), &fdset);
        max_fd = max(fd, fileno(fp)) + 1;
        select(max_fd, &fdset, NULL, NULL, NULL);
        
        if (FD_ISSET(fd, &fdset)) {
            if ( (n=read(fd, recvline, sizeof(recvline))) == 0) {
                if (stdioeof == 0) {
                    err_quit("str_cli: server terminated");
                } else {
                    return;
                }
            }
            Writen(fileno(stdout), recvline, n);
        }

        if (FD_ISSET(fileno(fp), &fdset)) {
            if ( (n=read(fileno(fp), readline, sizeof(readline))) == 0) {
                shutdown(fd, SHUT_WR);
                FD_CLR(fileno(fp), &fdset);
                stdioeof = 1;
                continue;
            }
            Writen(fd, readline, n);
        }
    }
}
